#!/usr/bin/env python
# coding: utf-8

# In[20]:


#%%
from vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting
from vnpy.app.cta_strategy.strategies.high_frequency_1 import (
    MultiTimeframeStrategy,
)
from vnpy.app.cta_strategy.base import BacktestingMode
# from vnpy.app.cta_strategy.strategies.atr_rsi_strategy import AtrRsiStrategy
from datetime import datetime
import concurrent.futures
import multiprocessing
import pandas as pd
# In[21]:

import copy
#%%
def backtest(symbol):
    engine = BacktestingEngine()
    engine.set_parameters(
        vt_symbol="{}.LOCAL".format(symbol),
        interval="1m",
        start=datetime(2021, 7, 1),
        end=datetime(2021, 8, 6),
        rate=2/10000,
        slippage=0,
        size=1,
        pricetick=0.2,
        capital=20_000,
        mode=BacktestingMode.TICK
    )

    engine.add_strategy(MultiTimeframeStrategy, {})


    # In[22]:


    #%%
    engine.load_data()
    engine.run_backtesting()


    return symbol,engine
def backtest2(engine):
    return engine.calculate_result(),engine.logs
    
if __name__ == '__main__':
    # 衍生信号
    __spec__ = "ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>)"

    engines={}
#     symbols=['AP', 'CJ', 'FU', 'EB', 'EG', 'CS', 'CF', 'HC', 'BU', 'JD', 'AL', 'CU', 'I', 'J']+[ 'JM', 'MA', 'M', 'OI', 'P', 'PP', 'RB', 'NI', 'SF', 'RU']+['RM', 'SM', 'PB', 'SA', 'SP', 'UR', 'SR', 'TA', 'ZC', 'V', 'Y', 'SS', 'ZN']
    symbols=['ss']
    df=pd.DataFrame()
    logs=[]
    with concurrent.futures.ProcessPoolExecutor(
            max_workers=multiprocessing.cpu_count() - 1) as executor:
        futures = [
            executor.submit(backtest,symbol)
            for symbol in symbols
        ]

        for future in concurrent.futures.as_completed(futures):
            symbol,engine=future.result()
            engines[symbol]=engine

            if future.exception():
                print(future.exception())
    with concurrent.futures.ProcessPoolExecutor(
            max_workers=multiprocessing.cpu_count() - 1) as executor2:

        # print(symbols)
    
        futures2 = [
            executor2.submit(backtest2,engine)
            for engine in engines.values()
        ]
        
        for future2 in concurrent.futures.as_completed(futures2):
            df_,logs_=future2.result()
            df=pd.concat((df,df_))
            logs.extend(logs_)
            if future2.exception():
                print(future2.exception())
        

    


# In[13]:


# setting = OptimizationSetting()
# setting.set_target("sharpe_ratio")
# setting.add_parameter("atr_length", 3, 39, 1)
# setting.add_parameter("atr_ma_length", 10, 30, 1)

# engine.run_ga_optimization(setting)
